
import axios from 'axios'
import qs from 'qs'
import { baseURL, requstPromise } from '../utils/utils'
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.transformRequest = [function (data) {
//   let ret = ''
//   for (let it in data) {
//     ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
//   }
//   return ret
// }]

axios.defaults.baseURL = baseURL
const api = {
    async get(url, data) {
        try {
            console.log(data)
            let res = await axios.get(url, {
                params: {
                    ...data
                }
            })
            res = res.data
            return requstPromise(res)
        } catch (err) {
            console.log('请求出错')
            console.log(err)
        }
    },
    async post(url, data) {
        let query = data instanceof Object ? data : {}
        try {
            let res = await axios.post(url, qs.stringify(query), {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            })
            res = res.data
            return requstPromise(res)
        } catch (err) {
            console.log('请求出错')
            console.log(err)
        }
    }
}

axios.interceptors.request.use((request) => {
    // 在发送请求之前做些什么
    // console.log(`发起请求：path:${request.url}，baseURL:${request.baseURL}`)
    // console.log(`openid：${store.state.openId}`)
    // if (request.url != 'api/wx/getAuth') {
    //     let openid = store.state.openid
    //     console.log(`请求前添加openid：${store.state.openid}`)
    //     request.headers["openid"] = openid;
    // }
    return request
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
})

export default api
